//
//  TVParser.m
//  TVLive
//
//  Created by sid on 29/05/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TVParser.h"


@implementation TVParser


- (NSString *)parseAddrAndGetVideoURL:(NSString *)url
{
	NSError *error = nil;
	
	NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url] options:0 error:&error];
	
	if (error != nil)
	{
		NSLog(@"Error: %@", error);
		return nil;
	}
	
	TFHppleElement *element;
	
	xpathParser = [[TFHpple alloc] initWithHTMLData:data];
	
	NSArray *elements = [xpathParser search:@"//video"];//@"//div[2]/div[2]/video"];
	
	NSString *iTv = nil;
	if ([elements count] > 0)
	{
		element = [elements objectAtIndex:0];
 
		NSString *tmp = [[NSString stringWithFormat:@"%@", element] stringByReplacingOccurrencesOfString:@"nodeAttributeArray =" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"nodeName = video;" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"(" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@");" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"{" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"}" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"attributeName =" withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"attributeName = " withString:@""];
		tmp = [[NSString stringWithFormat:@"%@", tmp] stringByReplacingOccurrencesOfString:@"nodeContent = " withString:@""];
		 
		NSArray *components = [tmp componentsSeparatedByString:@","];
		NSMutableDictionary *dict = [NSMutableDictionary new];
		
		for (id item in components)
		{
			NSArray *itemTemp = [item componentsSeparatedByString:@";"];
			[dict setValue:[[[[itemTemp objectAtIndex:1] stringByReplacingOccurrencesOfString:@"\"" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"\n" withString:@""] forKey:[[[itemTemp objectAtIndex:0] stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""]];
		}
		
		/*
		for (id key in dict)
		{
			NSLog(@"Key: %@, Value: %@", key, [dict valueForKey:key]);
		}
		 */
		
		iTv = [dict valueForKey:@"src"];
	}
	else 
	{
		return nil;
	}

	return iTv;
}

@end
